package net.easyjava.web.controller;


import com.alibaba.fastjson.JSONObject;
import net.easyjava.framework.web.security.UserSecurityAdminCookie;
import net.easyjava.framework.web.security.UserSecurityBean;
import net.easyjava.framework.web.security.UserSecurityCookie;
import net.easyjava.tools.model.ModelBean;
import net.easyjava.tools.model.ModelConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * Created by wenxiaoning on 15/12/18.
 */
public class BaseController {
    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());
    /**
     * CONTENT_TYPE_JSONP = "application/javascript";
     */
    public static final String CONTENT_TYPE_JSONP = "application/javascript;charset=UTF-8";
    public static final String CONTENT_TYPE_TEXT = "text/html;charset=UTF-8";

    /**
     * 参数错误时返回固定语句
     * @param key
     * @return
     */
    public String paramError(String key){
        String message = String.format(ModelConstants.MESSAGE_PARAM_ERROR,key);
        return message;
    }

    /**
     * 兼容jsonp的返回格式
     * @param model ModelBean
     * @param request
     * @param response
     * @return
     */
    public ModelBean model(ModelBean model,HttpServletRequest request,HttpServletResponse response){
        Map<String,String[]> params = request.getParameterMap();
        logger.info("返回结果概要 status:{},message:{},timestamp:{}",new Object[]{model.getStatus(),model.getMessage(),model.getMessage()});
        if(params.containsKey("callback")){
            try {
                response.setContentType(CONTENT_TYPE_TEXT);
                PrintWriter out = response.getWriter();
                out.write(new String(params.get("callback")[0] + "("));
                out.write(JSONObject.toJSONString(model));
                out.write(new String(");"));
            } catch (IOException e) {
                logger.error(e.getMessage(), e.fillInStackTrace());
            }
            logger.info("通过jsonp格式输出数据,callback:{}",params.get("callback")[0]);
            return null;
        }else{
            logger.info("通过json格式返回接口");
            return model;
        }
    }


    @Resource
    private UserSecurityCookie userSecurityCookie;

    /**
     * 获取登陆用户id
     * @return
     */
    protected String getUserId(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        UserSecurityBean userSecurityBean  = userSecurityCookie.getUserSecurityBean(request);
        if(userSecurityBean == null){
            logger.info("cookie 中没有登陆用户");
            return null;
        }
        logger.info("登陆用户信息:{}",userSecurityBean.toString());
        return userSecurityBean.getUserId();
    }
}
